package com.syn.vr.activity;

import android.Manifest;
import android.app.PendingIntent;
import android.content.Intent;
import android.graphics.Typeface;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.text.TextUtils;
import android.view.View;

import androidx.activity.result.ActivityResult;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;

import com.gaoyi.basemodule.baseCallback.IView;
import com.gaoyi.basemodule.baseUtil.AppUtil;
import com.gaoyi.basemodule.baseUtil.DateFormatUtil;
import com.gaoyi.basemodule.baseUtil.DensityUtil;
import com.gaoyi.basemodule.baseUtil.LanguageUtils;
import com.gaoyi.basemodule.baseUtil.PermissionUtils;
import com.gaoyi.basemodule.baseUtil.SPUtil;
import com.gaoyi.basemodule.baseUtil.ToastUtil;
import com.gaoyi.basemodule.baseUtil.WindowUtil;
import com.gaoyi.basemodule.baseact.BaseActivity;
import com.gaoyi.basemodule.basebean.Event;
import com.gaoyi.basemodule.baseconstant.SPName;
import com.gaoyi.basemodule.basedialog.LoadingDialogUtils;
import com.syn.vr.R;
import com.syn.vr.bean.CourseDto;
import com.syn.vr.bean.ShortDto;
import com.syn.vr.constant.ApiStatus;
import com.syn.vr.constant.BundleKeyName;
import com.syn.vr.control.CoursePopupWindow;
import com.syn.vr.control.ShortPopupWindow;
import com.syn.vr.control.UploadStatusDialog;
import com.syn.vr.databinding.ActivityMainBinding;
import com.syn.vr.util.FileUtil;
import com.syn.vr.util.MyTextUtil;
import com.syn.vr.vm.MainViewModel;

import java.util.Date;
import java.util.List;
import java.util.Map;

public class MainActivity extends BaseActivity<ActivityMainBinding, MainViewModel> implements IView {

    private ShortPopupWindow mItemPopupWindow;
    private CoursePopupWindow mCoursePopupWindow;
    private String mProjId;
    private Date mSwipeDate;
    private CourseDto mCourse;
    private NfcAdapter mNfcAdapter;
    private String mWorkerName, mWorkerId;

    @Override
    protected void event(Event event) {

    }

    @Override
    protected void onRequestPermissionsResult(Map<String, Boolean> result) {

    }

    @Override
    protected void onActivityResult(int requestCode, ActivityResult result) {

    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!SPUtil.getInstance().getBoolean(SPName.OPEN_CIC, false)) {
            startNfc();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mNfcAdapter != null && !SPUtil.getInstance().getBoolean(SPName.OPEN_CIC, false)) {
            pauseNfc();
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        String action = intent.getAction();
        if (TextUtils.isEmpty(action)) {
            showCardNo(intent.getStringExtra(BundleKeyName.CARD_NO));
            return;
        }
        if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action) ||
                NfcAdapter.ACTION_TECH_DISCOVERED.equals(action) ||
                NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)) {
            final Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
            if (tag != null) {
                String num = String.valueOf(MyTextUtil.toDec(tag.getId()));
                String time = DateFormatUtil.DateTimeToStr(new Date(), "yyyy-MM-dd HH:mm:ss");
                FileUtil.writeLog(this, "SwipeCardLog", num + "," + time + System.lineSeparator());
                showCardNo(num);
            }
        }
    }

    private void showCardNo(String cardNo) {
        mBinding.etCardNum.setText(cardNo);
        mSwipeDate = new Date();
        mBinding.tvTime.setVisibility(View.VISIBLE);
        mBinding.btnConfirm.setVisibility(View.VISIBLE);
        mBinding.tvTime.setText(getString(R.string.swipe_card_date, DateFormatUtil.DateTimeToStr(mSwipeDate, "dd-MM-yyyy HH:mm:ss")));
        mViewModel.getWorker(cardNo);
    }

    @Override
    protected void initView() {
        WindowUtil.setWindowDecorView(this);
        mPermissionsResult = registerForPermissionsResult();
        PermissionUtils.addPermission(this, new String[]{
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE}, mPermissionsResult);
        mNfcAdapter = NfcAdapter.getDefaultAdapter(this);

        Typeface typeface = Typeface.createFromAsset(mContext.getAssets(), "Oswald-Bold.ttf");
        mBinding.tvMainTitle.setTypeface(typeface);
        mBinding.tvItem.setOnClickListener(view -> showSite());
        mBinding.tvCourse.setOnClickListener(view -> showCourse());
        mBinding.ivMenu.setOnClickListener(view -> {
            closePopupWindow();
            mBinding.drawerLayout.openDrawer(GravityCompat.START);
        });
        mBinding.tvSetting.setOnClickListener(view -> {
            mBinding.drawerLayout.closeDrawer(GravityCompat.START);
            startActivity(new Intent(this, SettingActivity.class));
        });
        mBinding.btnConfirm.setOnClickListener(view -> {
            closePopupWindow();
            String cardNo = mBinding.etCardNum.getText().toString();
//            String cardNo = MyTextUtil.getEtText(mBinding.etCardNum);
            if (TextUtils.isEmpty(cardNo)) {
                ToastUtil.showToast(R.string.swipe_card_hint);
                return;
            }
            String workerName = MyTextUtil.getEtText(mBinding.etWorkerName);
            if (TextUtils.isEmpty(workerName)) {
                ToastUtil.showToast(R.string.worker_name_hint);
                return;
            }
            if (TextUtils.isEmpty(mProjId)) {
                ToastUtil.showToast(R.string.p_item_name);
                return;
            }
            if (mCourse == null) {
                ToastUtil.showToast(R.string.p_course_name);
                return;
            }
            String workerId = "";
            if (mWorkerName != null && mWorkerName.equals(workerName)) {
                workerId = mWorkerId;
            }
            mViewModel.upload(cardNo, workerName, mProjId, mCourse.getId(), mCourse.getName(), mSwipeDate, workerId);
        });
        // 禁止手势滑动
        mBinding.drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
        mBinding.viewOpenCic.setChecked(SPUtil.getInstance().getBoolean(SPName.OPEN_CIC, false));
        mBinding.viewOpenCic.setOnCheckedChangeListener((compoundButton, b) -> {
            if (b) {
                startNfc();
            } else {
                pauseNfc();
            }
            SPUtil.getInstance().putBoolean(SPName.OPEN_CIC, b);
        });
        mBinding.tvVersion.setText(getString(R.string.version, AppUtil.getVersion()));
        mBinding.etCardNum.setOnFocusChangeListener((view, b) -> {
            if (b) {
                closePopupWindow();
            }
        });
        mBinding.etWorkerName.setOnFocusChangeListener((view, b) -> {
            if (b) {
                closePopupWindow();
            }
        });
    }

    private void showSite() {
        if (mItemPopupWindow != null && mItemPopupWindow.isShowing()) {
            mItemPopupWindow.dismiss();
            return;
        }
        mViewModel.getSites();
    }

    private void showCourse() {
        if (mCoursePopupWindow != null && mCoursePopupWindow.isShowing()) {
            mCoursePopupWindow.dismiss();
            return;
        }
        mViewModel.getCourses();
    }

    private void startNfc() {
        if (mNfcAdapter != null && mNfcAdapter.isEnabled()) {
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
                    MainActivity.class).addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING), PendingIntent.FLAG_UPDATE_CURRENT);
            mNfcAdapter.enableForegroundDispatch(this, pendingIntent, null, null);
        }
    }

    private void pauseNfc() {
        if (mNfcAdapter.isEnabled()) {
            mNfcAdapter.disableForegroundDispatch(this);
        }
    }

    private void closePopupWindow() {
        if (mItemPopupWindow != null && mItemPopupWindow.isShowing()) {
            mItemPopupWindow.dismiss();
        }
        if (mCoursePopupWindow != null && mCoursePopupWindow.isShowing()) {
            mCoursePopupWindow.dismiss();
        }
    }

    private void showItemPopupWindow(List<ShortDto> data) {
        if (mCoursePopupWindow != null && mCoursePopupWindow.isShowing()) {
            mCoursePopupWindow.dismiss();
        }
        if (mItemPopupWindow == null) {
            mItemPopupWindow = new ShortPopupWindow(mContext);
            mItemPopupWindow.setHeight(DensityUtil.dp2px(170));
            mItemPopupWindow.setAnchorView(mBinding.tvItem);
            mItemPopupWindow.setOnItemClickListener((adapterView, view, i, l) -> {
                mItemPopupWindow.dismiss();
                if (mProjId.equals(data.get(i).getId())) {
                    return;
                }
                ShortDto shortDto = data.get(i);
                SPUtil.getInstance().putString(SPName.PROJ_ID, shortDto.getId());
                SPUtil.getInstance().putString(SPName.PROJ_NAME, shortDto.getName());
                mProjId = shortDto.getId();
                mBinding.tvItem.setText(shortDto.getName());
                mCourse = null;
                mBinding.tvCourse.setText("");
            });
            mItemPopupWindow.setOnDismissListener(() -> mBinding.tvItem.setSelected(false));
        }
        for (ShortDto dto : data) {
            if (dto.getId().equals(mProjId)) {
                dto.setSelect(true);
            }
        }
        mItemPopupWindow.setData(data);
        if (mItemPopupWindow.isShowing()) {
            mItemPopupWindow.dismiss();
        } else {
            mBinding.tvItem.setSelected(true);
            mItemPopupWindow.show();
        }
    }

    @Override
    protected void onDestroy() {
        closePopupWindow();
        super.onDestroy();
    }

    private void showCoursePopupWindow(List<CourseDto> data) {
        if (mCoursePopupWindow == null) {
            mCoursePopupWindow = new CoursePopupWindow(mContext);
            mCoursePopupWindow.setHeight(DensityUtil.dp2px(170));
            mCoursePopupWindow.setAnchorView(mBinding.tvCourse);
            mCoursePopupWindow.setOnItemClickListener((adapterView, view, i, l) -> {
                mCourse = data.get(i);
                mBinding.tvCourse.setText(mCourse.getName());
                mCoursePopupWindow.dismiss();
            });
            mCoursePopupWindow.setOnDismissListener(() -> mBinding.tvCourse.setSelected(false));
        }
        if (mCourse != null) {
            for (int i = 0; i < data.size(); i++) {
                if (data.get(i).getId().equals(mCourse.getId())) {
                    data.get(i).setSelect(true);
                }
            }
        }
        mCoursePopupWindow.setData(data);
        if (mCoursePopupWindow.isShowing()) {
            mCoursePopupWindow.dismiss();
            mBinding.tvCourse.setSelected(false);
        } else {
            mBinding.tvCourse.setSelected(true);
            mCoursePopupWindow.show();
        }
    }

    @Override
    protected int initVariable() {
        return 0;
    }

    @Override
    protected void initLiveData() {
        mViewModel.getResultCode().observe(this, integer -> {
            mBinding.etCardNum.setText("");
            mBinding.etWorkerName.setText("");
            mWorkerId = "";
            mWorkerName = "";
            mCourse = null;
            mBinding.tvCourse.setText("");
            mBinding.tvTime.setVisibility(View.GONE);
            mBinding.btnConfirm.setVisibility(View.GONE);
            UploadStatusDialog.newInstance(this,
                    getString(integer == ApiStatus.SUCCESS ? R.string.upload_success : R.string.save_success)).show(getSupportFragmentManager());
        });
        mViewModel.getSiteList().observe(this, this::showItemPopupWindow);
        mViewModel.getCourseList().observe(this, this::showCoursePopupWindow);
        mViewModel.getWorker().observe(this, (bean) -> {
            mWorkerId = bean.getId();
            mWorkerName = LanguageUtils.getInstance().isEnglish() ? bean.getEnName() : bean.getCnName();
            mBinding.etWorkerName.setText(mWorkerName);
        });
    }

    @Override
    protected void initData() {
        mBinding.tvCardNumTitle.setText(MyTextUtil.setStar(this, R.string.card_num));
        mBinding.tvWorkerNameTitle.setText(MyTextUtil.setStar(this, R.string.worker_name));

        mBinding.tvItem.setText(SPUtil.getInstance().getString(SPName.PROJ_NAME));
        mProjId = SPUtil.getInstance().getString(SPName.PROJ_ID);
    }

    @Override
    public void showLoading() {
        LoadingDialogUtils.getInstance().showLoading(mContext);
    }

    @Override
    public void hideLoading() {
        LoadingDialogUtils.getInstance().dismiss();
    }
}